package com.cm.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.cm.common.core.Result;
import com.cm.gateway.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @类 名：AuthGatewayFilter </br>
 * @描 述：</br>
 * @日 期：2020/9/21 8:53</br>
 * @作 者：常明</br>
 * @版 本：1.0.0
 * @since JDK 1.8
 */
@Slf4j
@Component
public class  AuthGatewayFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("网关过滤器");
        ServerHttpRequest request  = exchange.getRequest();
        log.info("{}", request .getPath());
        ServerHttpResponse response = exchange.getResponse();

        if (request.getPath().toString().contains("login")||request.getPath().toString().contains("type")||request.getPath().toString().contains("goods")||request.getPath().toString().contains("user")||request.getPath().toString().contains("brand")) {
            return chain.filter(exchange);
        }
        // 获取令牌
        HttpHeaders headers = request.getHeaders();
        List<String> tokens = headers.get("token");
        Result result = Result.fail("没有认证");
        if (null != tokens && tokens.size() > 0) {
            String token = tokens.get(0);
            // TODO 有令牌
            if (token!=null&&token!="") {
                String username = JwtUtils.getUsername(token);
                String password = "ababa";
                // 防篡改
                if (JwtUtils.verify(token, username, password)) {
                    return chain.filter(exchange);
                }else{
                    String account=JwtUtils.getAccount(token);
                    String password1="userPassword";
                    if (JwtUtils.verifyUser(token, account, password1)){
                        return chain.filter(exchange);
                    } else{
                        result =new Result("5555",false,"令牌不正确");
                    }
                }
            }
        }
        // 设置body
        String warningStr = JSON.toJSONString(result);
        // 响应数据
        DataBuffer bodyDataBuffer = response.bufferFactory().wrap(warningStr.getBytes());
        return response.writeWith(Mono.just(bodyDataBuffer));
    }
}

